/*
 * @LastEditors: zhouyaxue
 * @Date: 2022-09-06 12:01:05
 * @LastEditTime: 2023-01-09 10:44:55
 */

import axios from 'axios';
import get from 'lodash/get';
import { ElLoading, ElMessage } from 'element-plus'; //ElMessage
import router from '../router/index';
import { setSession, getSession } from '@/public/utils';
declare module 'axios' {
  export interface AxiosRequestConfig {
    loading?: string;
  }
}

// console.log(import.meta.env.VITE_APP_BASE_API, 'import.meta.env.VUE_APP_BASE_API')

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  // baseURL: process.env.VUE_APP_BASE_URL, // process.env.VUE_APP_BASE_URL
  // baseURL: '/data-deal-website', // process.env.VUE_APP_BASE_URL
  timeout: 10000, // 请求超时时间
  headers: {
    Accept: "application/json, text/plain, */*",
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest"
  },
});

// 异常拦截处理器
interface Error {
  [propName: string]: any;
}
const errorHandler = (error: Error) => {
  const { loadingInstance } = error.config;
  if (loadingInstance) {
    loadingInstance.close();
  }
  const status = get(error, 'response.status');
  let message;
  switch (status) {
    case 400:
      message = '请求错误';
      break;
    case 401: {
      message = '登录失效,请重新登录';
      router.push({ path: '/' });
      break;
    }
    case 403:
      message = '拒绝访问';
      break;
    case 404:
      message = `请求地址出错: ${error.response.config.url}`;
      break;
    case 408:
      message = '请求超时';
      break;
    case 500:
      message = '服务器内部错误';
      break;
    case 501:
      message = '服务未实现';
      break;
    case 502:
      message = '网关错误';
      break;
    case 503:
      message = '服务不可用';
      break;
    case 504:
      message = '网关超时';
      break;
    case 505:
      message = 'HTTP版本不受支持';
      break;
    default:
      break;
  }
  // ElMessage.error(message);
  ElMessage.error(message);
  // console.log(message);
  return Promise.reject(error);
};

interface Config {
  [propName: string]: any;
}
// request interceptor
request.interceptors.request.use((config: Config) => {
  if (config.loading) {
    config.loadingInstance = ElLoading.service({
      target: config.loading,
      background: 'rgba(255,255,255,0.2)',
      text: config.loadingText || '正在加载中...',
      customClass: 'loadingClass',
    });
  }

  return config;
}, errorHandler);

interface Response {
  [propName: string]: any;
}
// response interceptor
request.interceptors.response.use((response: Response) => {
  
  const { loadingInstance } = response.config;
  if (loadingInstance) {
    loadingInstance.close();
  }
  const dataAxios = response.config.responseType === 'blob' ? response : response.data;
  // 这个状态码是和后端约定的
  console.log(response.config.url, 'queryApplyMembersInfo');

  return dataAxios;
}, errorHandler);
export default request;
